<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Comment extends Model
{
    protected $guarded = [];
    protected $table = 'evaluates';

    const CREATED_AT = 'create_time';
    const UPDATED_AT = 'update_time';

    //用户基本信息
    public function consumer()
    {
        return $this->hasOne(Consumer::class,'id','cid');
    }

    //用户详细信息
    public function consumerInfo()
    {
        return $this->hasOne(ConsumerInfo::class,'cid','cid');
    }

    //评价码值记录
    public function evaluateRecord()
    {
        return $this->hasMany(EvaluateTagRecord::class,'evaluate_id','id');
    }

    //评论标签
    public function commentTag()
    {
        return $this->hasMany(CommentTagRecord::class,'comment_id','id');
    }



    /**评价列表。select:查询评价，分页，；download:导出评价，不分页。
     * @param $query
     * @param string $select
     * @param string $type
     * @return mixed
     */
    function comment($query,$select = '*',$type = 'select'){
        $where = [];

        //选择了评价类型
        if($query->type){
            $where[] = ['evaluate_type',$query->type];
        }
        //评论日期
        if($query->start_date){
            $where[] = ['create_time','>=',$query->start_date . ' 00:00:00'];
        }
        if($query->end_date){
            $where[] = ['create_time','<=',$query->end_date . ' 23:59:59'];
        }

        if($query->username){
            $where[] = ['consumer_infos.username',$query->username];
        }
        if($query->phone){
            $where[] = ['consumer_infos.phone',$query->phone];
        }
        if($query->content){
            $where[] = ['content','like', $query->content . '%'];
        }
        if($query->company_id){
            $where[] = ['company_id', $query->company_id];
        }

        //$comment = $this->join('consumer_infos','evaluates.cid','consumer_infos.cid')->where($where);
        $comment = $this->leftJoin('consumer_infos','evaluates.cid','consumer_infos.cid')
            ->leftJoin('evaluate_tag_records','evaluates.id','evaluate_tag_records.evaluate_id')->where($where);

        //TODO  满意度


        if($query->id){//指定了某几条评价
            $comment = $comment->whereIn('evaluates.id',[$query->id]);
        }

        if($type == 'download'){
            return $comment->select($select)->orderBy('evaluates.create_time')->get();
        }
        return $comment->select($select)->orderBy('evaluates.create_time')->paginate();
    }
}
